<?php

namespace app\admin\controller\systemConfig;
use app\admin\model\ConfigGroup as ConfigGroupModel;
use app\common\controller\Backend;
use Exception;
use think\db\exception\DbException;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

class ConfigGroup extends Backend
{
    protected $model = null;

    protected $noNeedLogin = [];
    /**
     * 查看请求返回的主表字段控制
     */
    protected $indexField = ['id', 'name', 'title', 'weigh', 'status', 'update_time', 'create_time', 'create_time'];
    /**
     * 新增/编辑时，对前端发送的字段进行排除（忽略不入库）
     */
    protected $preExcludeFields = ['create_time', 'update_time'];

    public function initialize()
    {
        parent::initialize();
        $this->model = new ConfigGroupModel();
    }

    public function index()
    {
        try {
            // 剥去字符串中的HTML标签以及左右两边的空格
            $this->request->filter(['strip_tags', 'trim']);
            if (stringToBoolean($this->request->param('select'))) {
                // 下拉框数据接口
                $this->select();
            }
            // 生成搜索条件、排序等
            list($where, $alias, $limit, $order) = $this->queryBuilder();
            $res = $this->model
                ->field($this->indexField)
                ->withJoin($this->withJoinTable, $this->withJoinType)
                ->alias($alias)
                ->where($where)
                ->order($order)
                ->paginate($limit);

            $this->success('', [
                'list'   => $res->items(),
                'total'  => $res->total(),
                'remark' => get_route_remark(),
            ]);
        } catch (DbException $ex) {
            $this->success('', [
                'list'   => [],
                'total'  => 0,
                'remark' => get_route_remark(),
            ]);
        }
    }

    public function edit($id = null){
        if (empty($id)) {
            $this->error(__('Record not found'));
        }
        $row = $this->model->find($id);
        if(!$row){
            $this->error('未找到记录');
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if($this->request->isPost()){
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) {
                            // 启用模型场景验证
                            $validate->scene('edit');
                        }
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|Exception|PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }
        $this->success('', [
            'row' => $row
        ]);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            // 模型验证
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) {
                            // 启用模型场景验证
                            $validate->scene('add');
                        }
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|Exception|PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }
        $this->error(__('Parameter error'));
    }

    /**
     * 修改分组状态
     * @param $id
     * @return void
     */
    public function editStatus($id = null){
        if($this->request->isPost()){
            if (empty($id)) {
                $this->error(__('Record not found'));
            }
            $row = $this->model->find($id);
            if(!$row){
                $this->error('未找到记录');
            }

            $dataLimitAdminIds = $this->getDataLimitAdminIds();
            if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
                $this->error(__('You have no permission'));
            }
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) {
                            // 启用模型场景验证
                            $validate->scene('editStatus');
                        }
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|Exception|PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }
    }

    public function select()
    {
        $data = $this->model->order('weigh DESC,id ASC')->select()->toArray();
        $this->success('', [
            'options' => $data
        ]);
    }

}